﻿using System;
using System.Collections.Generic;
using BitButterECS.Component;
using BitButterECS.Event;
using BitButterECS.Event.EventArgs;

namespace BitButterECS.Entity
{
    public abstract class BaseEntity
    {
        public BaseEntity()
        {
            Manager.AddEntity(this);
        }

        public int ID
        {
            get => id;
            set
            {
                if (!IsManaged)
                {
                    id = value;
                }
            }
        }
        int id = -1;

        public bool IsManaged => Manager.HasEntity(ID);

        public virtual void Remove()
        {
            Manager.RemoveEntity(this);
        }

        public virtual void AttachComponent(BaseComponent component)
        {
            if (!ComponentCollection.ContainsKey(component.GetType()))
            {
                component.AttachToEntity(this);
                ComponentCollection.Add(component.GetType(), component);
                AttachComponentEvent.RaiseEvent(this, new AttachComponentEventArgs(this, component));
            }
        }

        public virtual void DetachComponent(BaseComponent component)
        {
            if (ComponentCollection.ContainsKey(component.GetType()))
            {
                component.DetachFromEntity();
                ComponentCollection.Remove(component.GetType());
                DetachComponentEvent.RaiseEvent(this, new DetachComponentEventArgs(this, component));
            }
        }

        public BaseComponent this[Type queryType]
        {
            get
            {
                if (ComponentCollection.ContainsKey(queryType))
                {
                    return ComponentCollection[queryType];
                }
                return null;
            }
        }

        Dictionary<Type, BaseComponent> ComponentCollection
        {
            get
            {
                if (componentCollection == null)
                {
                    componentCollection = new Dictionary<Type, BaseComponent>();
                }
                return componentCollection;
            }
        }
        Dictionary<Type, BaseComponent> componentCollection;

        protected EntityManager Manager => EntityManager.Instance;
    }
}
